package com.zhj.leetcode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 力扣 938 二叉搜索树范围和(low 低， high 高)
 */
public class Test938 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(10);
        root.left = new TreeNode(5);
        root.right = new TreeNode(15);
        root.left.left = new TreeNode(3);
        root.left.right = new TreeNode(7);
        root.right.right = new TreeNode(18);
        System.out.println(getSumBFS(root, 0, 15));
    }

    /**
     * 递归
     * @param root
     * @param low
     * @param high
     * @return
     */
    public static int getSum(TreeNode root, int low, int high) {
        if (root == null) {
            return 0;
        }
        int leftSum = getSum(root.left, low, high);
        int rightSum = getSum(root.right, low, high);
        int result = leftSum + rightSum;
        if (low <= root.val && root.val <= high) {
            result = result + root.val;
        }
        return result;
    }

    /**
     * bfs
     * @param root
     * @param low
     * @param high
     * @return
     */
    public static int getSumBFS(TreeNode root, int low, int high) {
        if (root == null) {
            return 0;
        }
        int sum = 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()){
            int size = queue.size();
            while (size > 0) {
                TreeNode cur = queue.poll();
                if (low <= cur.val && cur.val <= high) {
                    sum = sum + cur.val;
                }
                if (cur.left != null) {
                    queue.add(cur.left);
                }
                if (cur.right != null) {
                    queue.add(cur.right);
                }
                size--;
            }
        }
        return sum;
    }

}
